package cn.ybz21.hibot.topic_process_center.app;

import java.io.IOException;

import cn.ybz21.hibot.bean.App;
import cn.ybz21.hibot.bean.AppState;
import cn.ybz21.hibot.db.service.AppDAO;
import cn.ybz21.hibot.net.NetCenter;
import cn.ybz21.hibot.topic_process_center.base.BaseCenter;
import cn.ybz21.hibot.util.DownloadUtil;
import cn.ybz21.hibot.util.FileUtil;
import cn.ybz21.hibot.util.StaticValues;
import cn.ybz21.hibot.util.ZipUtil;

import com.google.gson.Gson;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttTopic;

public class AppDownloadCenter implements BaseCenter {
	@Override
	public void doAction(MqttTopic topic, MqttMessage message) {
		System.out.println("---------------------\ndownload app");
		System.out.println(message.toString());
		Gson gson = new Gson();
		App app = (App) gson.fromJson(message.toString(), App.class);
		try {
			process(app);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("end download app\n---------------------");
	}

	void process(App app) throws IOException {
		DownloadUtil.downloadFile(app.downloadLink, StaticValues.PATH_ZIP,
				app.name + ".zip");
		onFinish(app);
		ZipUtil.unzip(StaticValues.PATH_ZIP + "/" + app.name + ".zip",
				StaticValues.PATH_UNZIP);
		FileUtil.copyFolder(StaticValues.PATH_UNZIP + "/" + app.name,
				StaticValues.PATH_ROS_SRC + "/" + app.name);
		app.state=AppState.STOP;
		new AppDAO().addApp(app);
	}

	private void onFinish(App task) {
		String urlString = StaticValues.URL_FINISH_DOWNLOAD_TASK + "/"
				+ StaticValues.ID_CLIENT;
		String result = "";
		try {
			result = new NetCenter().httpGet(urlString);
		} catch (IOException e) {

			e.printStackTrace();
		}
		System.out.println("result:" + result);
	}
}
